package com.sleepsocial.web.connect;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sleepsocial.authentication.AuthenticationManager;
import com.sleepsocial.persistency.entity.oauth.OauthProvider;
import com.sleepsocial.persistency.entity.oauth.OauthUserProfile;
import com.sleepsocial.persistency.entity.user.UserProfile;
import com.sleepsocial.web.Web;

@Controller
public class WebConnectController extends Web {
    public static final String CONNECT_URL = WEB_BASE_URL + "/connect";

    private TwitterConnector   twitterConnector;

    @Autowired
    public void setTwitterConnector(TwitterConnector twitterConnector) {
        this.twitterConnector = twitterConnector;
    }

    @RequestMapping(value = CONNECT_URL, method = RequestMethod.GET)
    public void connect(Model model, HttpServletRequest req, HttpSession session) {

        UserProfile user = AuthenticationManager.getAuthenticatedUser(req);
        List<OauthUserProfile> profiles = user.getProfiles();

        for (OauthUserProfile profile : profiles) {
            model.addAttribute(profile.getProvider().name().toLowerCase(), profile);
        }
        // TODO create twitter auth url

        if (!model.containsAttribute(OauthProvider.TWITTER.name().toLowerCase())) {
            model.addAttribute("twitterurl", twitterConnector.getAuthorizeUrl(session));
        }
    }

}
